﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public class UniqueProcess
    {
        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        public static string Message = "该应用系统已经在运行！";

        /// <summary>
        /// 获取当前程序名已运行的进程，如果没有则返回null
        /// </summary>
        /// <returns></returns>
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //遍历与当前进程名称相同的进程列表
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    return process;
                }
            }
            return null;
        }

        /// <summary>
        /// 将进程主窗体显示到最前
        /// </summary>
        /// <param name="instance"></param>
        public static void HandleRunningInstance(Process instance)
        {
            MessageBox.Show(Message, "提示信息");
            IntPtr handle = instance.MainWindowHandle;
            //将进程显示在最前
            SwitchToThisWindow(handle, true);
        }
    }
}
